package com.leetcode.p0;

import com.bean.ListNode;
import com.utils.DataUtils;

import java.util.Comparator;
import java.util.PriorityQueue;

public class Test23 {

    public ListNode mergeKLists(ListNode[] lists) {
        ListNode pre = new ListNode();

        PriorityQueue<Integer> queue = new PriorityQueue<>(11, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });

        for (ListNode listNode : lists) {
            ListNode node = listNode;
            while (node != null) {
                queue.offer(node.val);
                node = node.next;
            }

        }

        ListNode next = null;

        while (!queue.isEmpty()) {
            ListNode temp = new ListNode(queue.poll());
            if (next != null) {
                next.next = temp;
            } else {
                pre.next = temp;
            }
            next = temp;
        }

        return pre.next;
    }

    public static void main(String[] args) {
        Test23 test = new Test23();

        ListNode l1 = DataUtils.getListNode(new int[]{1, 4, 5});
        ListNode l2 = DataUtils.getListNode(new int[]{1, 3, 4});
        ListNode l3 = DataUtils.getListNode(new int[]{2, 6});

        ListNode result = test.mergeKLists(new ListNode[]{l1, l2, l3});
        DataUtils.printListNode(result);
    }

}
